package com.aaa.filter;

import cn.hutool.Hutool;
import cn.hutool.json.JSONUtil;
import com.aaa.entity.Result;
import com.aaa.utils.JwtTool;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author ：Username 刘亦辰（59372312@qq.com）
 * @date ：Created in 2022/11/3 19:05
 * @description：
 * @modified By：
 * @version:
 */
@Component
public class JwtVerifyFilter extends OncePerRequestFilter {
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        response.setContentType("application/json;charset=utf-8");
        //0.获取请求路径
        String path = request.getRequestURI();
        System.out.println(path);
        //1.获取请求方式
        String method = request.getMethod();
        System.out.println(method);
        if ("POST".equals(method) && "/login".equals(path)){
            filterChain.doFilter(request,response);
            return;
        }
        //1.获取请求头上的token值。
        String token = request.getHeader("token");
        //2.判断是否携带请求token值.
        if (StringUtils.hasText(token)){
            //3.检验token是否有效.
            boolean b = JwtTool.verifyToken(token);
            if (b){
                //4.解析token内容
                Map<String, Object> tokenClaim = JwtTool.getTokenClaim(token);
                String username = tokenClaim.get("username").toString();
                List<String> list = (List<String>) tokenClaim.get("authorities");
                //5.把解析的结果封装到SecurtitContext中，可以交于security判断相应的权限
                List<SimpleGrantedAuthority> authorities = list.stream().map(item -> new SimpleGrantedAuthority(item)).collect(Collectors.toList());
                UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(username, null, authorities);
                SecurityContextHolder.getContext().setAuthentication(authenticationToken);
                filterChain.doFilter(request,response);
                return;
            }
        }
        //6. token为null或者token无效时。响应一个json数据.
        PrintWriter writer = response.getWriter();
        Result result = new Result(500,"token无效",null);
        String jsonStr = JSONUtil.toJsonStr(result);
        writer.println(jsonStr);
        writer.flush();
        writer.close();
    }
}